use crate::walk::BmbpLibPom;
use crate::BmbpArgs;
use reqwest::blocking::multipart::{Form, Part};
use std::path::PathBuf;

const UPLOAD_COMPONENT_API: &str = "/service/rest/v1/components";

pub fn upload_pom(args: &BmbpArgs, pom_lib: &[BmbpLibPom]) -> Result<(), String> {
    let repo_url = format!(
        "{}{}?repository={}",
        args.url, UPLOAD_COMPONENT_API, args.repo
    );
    println!("===>repo:{}", repo_url);
    let client = reqwest::blocking::Client::new();
    for item in pom_lib {
        if !item.jar_file.is_empty() {
            println!("start up :{}", item.jar_file);
            let mut form = Form::new();
            let pa = Part::file(PathBuf::from(item.jar_file.clone())).unwrap();
            form = form
                .text("maven2.groupId", item.group.clone())
                .text("maven2.artifactId", item.arti.clone())
                .text("maven2.version", item.version.clone())
                .part("maven2.asset1", pa)
                .text("maven2.asset1.extension", "jar");
            let builder = client
                .post(&repo_url)
                .basic_auth(args.user.clone(), Some(args.pass.clone()))
                .multipart(form);
            let res = builder.send().unwrap();
            println!("up_result:{}->{}", res.status(), item.jar_file)
        };
        if !item.pom_file.is_empty() {
            println!("start up :{}", item.pom_file);
            let mut form = Form::new();
            let pa = Part::file(PathBuf::from(item.pom_file.clone())).unwrap();
            form = form
                .text("maven2.groupId", item.group.clone())
                .text("maven2.artifactId", item.arti.clone())
                .text("maven2.version", item.version.clone())
                .part("maven2.asset1", pa)
                .text("maven2.asset1.extension", "pom");
            let builder = client
                .post(&repo_url)
                .basic_auth(args.user.clone(), Some(args.pass.clone()))
                .multipart(form);
            let res = builder.send().unwrap();
            println!("up_result:{}->{}", res.status(), item.pom_file)
        };
    }
    Ok(())
}
